/*
 * Copyright (c) www.bugull.com
 */

package com.bugull.farm.core.balancer;

import java.util.List;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.shared.SharedCount;
import org.apache.curator.utils.CloseableUtils;

/**
 *
 * @author Frank Wen(xbwen@hotmail.com)
 */
public class RoundRobinBalancer implements Balancer {
    
    private CuratorFramework zkClient;
    
    public RoundRobinBalancer(CuratorFramework zkClient){
        this.zkClient = zkClient;
    }

    @Override
    public String select(String workerType) throws Exception {
        List<String> workers = zkClient.getChildren().forPath(workerType);
        if(workers == null){
            return null;
        }
        int size = workers.size();
        if(size == 0){
            return null;
        }
        
        int round = -1;
        SharedCount sc = new SharedCount(zkClient, "/round", -1);
        boolean success = false;
        try {
            sc.start();
            while(!success){
                round = sc.getCount();
                round++;
                if(round >= Integer.MAX_VALUE){
                    round = -1;
                }
                success = sc.trySetCount(round);
            }
        }finally{
            CloseableUtils.closeQuietly(sc);
        }
        
        int index = round % size;
        return workers.get(index);
    }

}
